/*
Zebda javascript library
http://labs.cavorite.com/zebda
Copyright (C) 2006 Juan Manuel Caicedo

See zebda.js for full licence

*/

// Common functions

/**
 * Simple JSON parser
 */
if (!window.JSON){
    JSON = {
        parse: function(str){
            return eval('(' + str + ')');
        }
    };
}

/**
 * Removes trailing withspace
 */
String.prototype.trim = function(){
    return this.replace(/ /g, '');
};


/**
 * Javascript sets
 * 
 * Example:
 * var typeInSet = nodeType in set(2, 3, 4, 7, 8);
 *
 * http://laurens.vd.oever.nl/weblog/items2005/setsinjavascript/
 */
function set (){
    var result = {};
    for (var i = 0; i < arguments.length; i++){
        result[arguments[i]] = true;
    }
    return result;
}


/** 
 * Finds the position of a node
 *
 */
Element.getSiblingPosition = function(element){
    var pos = 0;
    while (element.previousSibling) {
        if (element.previousSibling.nodeType != 3){
            pos++;
        }
        element = element.previousSibling;
    }
    return pos;
};


/**
 * 
 *
 */
Element.getParentNodeByName = function(element, tagName){
    var par = element;
    while(par.tagName.toLowerCase() != tagName && par.parentNode) {
        par = par.parentNode;
    }
    return par;
};

/**
 *
 * @see    http://www.litotes.demon.co.uk/example_scripts/fastTableSort_src.html
 */
Element.getInnerText = function(element){
    if (!element || (typeof element).search(/string|undefined/) > -1)
        return element;

    if (element.innerText)
        return element.innerText;

    var rtn = '';
    var nodes = element.childNodes;
    var len = nodes.length;
    for (var i = 0; i < len; i++) {
        switch (nodes[i].nodeType) {
            case 1: //ELEMENT_NODE
                rtn += Element.getInnerText(nodes[i]);
                break;
            case 3: //TEXT_NODE
                rtn += nodes[i].nodeValue;
                break;
        }
    }
    return rtn;
};


/**
 * Sets the value of a form field
 * 
 */
Form.Element.setValue = function(element, value){
    element = $(element);
    els = ((element.tagName)) && [element] || element;

    $A(els).each(function(element){
        var elmType = element.tagName.toLowerCase();
        switch(elmType){
            case 'select':
                if (typeof(value) != 'object')
                    value = [value];

                $A(element.options).each(function(opt){
                    opt.selected = value.include(opt.value);
                });
                break;
            case 'input':
                if (element.type in set('radio', 'checkbox')){
                    element.checked = (element.value == value);
                }else{
                    element.value = value;
                }
        }
    });
}